package com.yyq.eduucenter.controller;

import com.google.gson.Gson;
import com.yyq.eduucenter.entity.UcenterMember;
import com.yyq.eduucenter.service.UcenterMemberService;
import com.yyq.eduucenter.utils.ConstantWx;
import com.yyq.eduucenter.utils.HttpClientUtils;
import com.yyq.result.JwtUtils;
import com.yyq.servicebase.exceptionhandler.YyqException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author yyq
 * @create 2021-04-30 16:18
 */
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxController {
    private String phone;
    @Autowired
    private UcenterMemberService service;
    //返回二维码
    @GetMapping("wxLogin/{mobile}")
    public String WxLogin(HttpSession session, @PathVariable String mobile){
        phone=mobile;
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWx.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new YyqException(20001,"获取验证码错误");
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名


        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWx.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }
    //返回二维码
    @GetMapping("wxLogin")
    public String WxLogin(HttpSession session){
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = ConstantWx.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new YyqException(20001,"获取验证码错误");
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名


        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWx.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }

    @GetMapping("callback")
    public String callback(String code, String state) {

        //得到授权临时票据code
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        //1 获取code值，临时票据，类似于验证码
        //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //拼接三个参数 ：id  秘钥 和 code值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWx.WX_OPEN_APP_ID,
                ConstantWx.WX_OPEN_APP_SECRET,
                code
        );

        //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
        //使用httpclient发送请求，得到返回结果

        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo = " + accessTokenInfo);
            Gson gson = new Gson();
            HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String openid= (String) accessTokenMap.get("openid");
            System.out.println("*****openid = " +openid);
            String access_token= (String) accessTokenMap.get("access_token");
           // int wxFlag=0;
            System.out.println(phone);
//           //TODO->微信登录
//            if(phone.length()==11){
//                wxFlag=1;
//                QueryWrapper<UcenterMember> wrapper=new QueryWrapper<>();
//                wrapper.eq("mobile",phone);
//                UcenterMember one = service.getOne(wrapper);
//                if(one!=null) {
//                    UcenterMember ucenterMember = new UcenterMember();
//                    ucenterMember.setId(one.getId());
//                    ucenterMember.setMobile(phone);
//                    ucenterMember.setOpenid(openid);
//                    boolean update = service.update(ucenterMember, null);
//                    if (update) {
//                        System.out.println("添加成功");
//                    }
//                }
//            }

            //检查opnid是否在数据库
            UcenterMember member;
            member=service.getByOpendId(openid);
            //member为空添加到数据库　不用请求微信
            if(member==null){
                //3 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String UserUrl=String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String UserInfo=HttpClientUtils.get(UserUrl);
                HashMap UserInfoMap = gson.fromJson(UserInfo, HashMap.class);
                String nickName =(String) UserInfoMap.get("nickname");
                String headimgurl=(String) UserInfoMap.get("headimgurl");
                System.out.println("*****Info = " + UserInfo+"**"+nickName+"**"+headimgurl+"**"+openid);
                UcenterMember member1=new UcenterMember();
                //保存用户到数据库
                member1.setOpenid(openid);
                member1.setNickname(nickName);
                member1.setAvatar(headimgurl);
                service.save(member1);

                //把用户信息用ＪＷｔ
                String jwtToken = JwtUtils.getJwtToken(member1.getId(), member1.getNickname());
                System.out.println(jwtToken);
                //最后：返回首页面，通过路径传递token字符串
                return "redirect:http://localhost:3000?token="+jwtToken;


            }
            else {
             //把用户信息用ＪＷｔ
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            System.out.println(jwtToken);
            //最后：返回首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token="+jwtToken;}

        } catch (Exception e) {
            throw  new YyqException(20001,"微信登录失败");

        }

    }
}
